import axios from 'axios'
import { showLoading, hideLoading } from './Loading';
import store from '@/store/index'

const apis = {
  production: 'http://localhost:80', // 线上 (生产环境)
  development: 'http://localhost:8081', // 本地 (开发环境)
  accessHomeData: '' // 其他api
}

// let baseUrl = process.env.NODE_ENV === 'production' ? apis.production : apis.development
let baseUrl = apis.development
export const request = (url, params, method, isJson) => {

  return new Promise((resolve,reject) => {
    axios({
      method: method,
      url: `${baseUrl}${url}`,
      data: method === 'post' ? params : '',
      timeout: 6000,
      transformRequest: [function(data) {
        if (isJson === 1) { // 判断是否json格式或者是表单提交形式
          return JSON.stringify(data)
        }
        let ret = '';
        for (let it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return ret // 便于直接取到内部data
      }],
      headers: {
        // 认证和请求方式
        'Content-Type': isJson === 1 ? 'application/json' : 'application/x-www-form-urlencoded',
        // 'authorization':'admin',
        'token': store.state.token,

      },
      params: method === 'get' ? params : '',
    }).then(res => {
      resolve(res.data)
    }).catch(err  =>{
      reject(err.data)
    })
  })
};

// uploadFileRequest  图片上传
export const uploadFileRequest = (url, data) => {
  return axios({
    method: 'post',
    url: `${baseUrl}${url}`,
    data: data,
    headers: {
      'Content-Type': 'multipart/form-data',
      'token': localStorage.getItem('token'),
      'authorization':'admin'
    }
  })
};

// post
export const postRequest = (options) => {
  return request(options.url, options.params, 'post', options.isJson)
};

// get
export const getRequest = (options) => {
  return request(options.url, options.params, 'get', options.isJson)
};

// 使用拦截器添加加载动画
axios.interceptors.request.use(
  config => {
    showLoading();
    return config
  },
  err => {
    hideLoading();
    return Promise.reject(err)
  }
);
// 关闭加载动画
axios.interceptors.response.use(
  response => {
    hideLoading();
    return response;
  },
  error => {
    hideLoading();
    return error.response;
  }
);
